import { ForbiddenException, Injectable } from '@nestjs/common';
import { CreateClassInfoDto } from './dto/create-class-info.dto';
import { UpdateClassInfoDto } from './dto/update-class-info.dto';
import { ClassInfo } from './entities/class-info.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GetClassInfoDto } from './dto/get-class-info.dto';
import { conditionUtilsLike } from '../utils/db.help';

@Injectable()
export class ClassInfoService {
  constructor(
    @InjectRepository(ClassInfo)
    private classInfoRepository: Repository<ClassInfo>,
  ) {}

  create(createClassInfoDto: CreateClassInfoDto) {
    return this.classInfoRepository.save(createClassInfoDto);
  }

  async findAll(query: GetClassInfoDto) {
    const { limit, page, blur } = query;
    let queryBuilder = await this.classInfoRepository.createQueryBuilder(
      'class_info',
    );

    if (blur) {
      queryBuilder = queryBuilder
        .orWhere('class_info.name LIKE :searchTerm', {
          searchTerm: `%${blur}%`,
        })
        .orWhere('class_info.class_code LIKE :searchTerm', {
          searchTerm: `%${blur}%`,
        });
    }

    const count = await queryBuilder.getCount();
    const content = await queryBuilder
      .skip((page - 1) * limit || 0)
      .take(limit || 10)
      .getMany();
    return {
      content,
      totalElements: count,
      totalPages: Number(page || 1),
    };
  }

  findDetail(id: number) {
    return this.classInfoRepository.findOne({ where: { id } });
  }

  async update(id: number, updateClassInfoDto: UpdateClassInfoDto) {
    const res = await this.findOne(id);
    if (!res.id) {
      throw new ForbiddenException('班级不存在');
    }
    const newRes = this.classInfoRepository.merge(res, updateClassInfoDto);
    return this.classInfoRepository.save(newRes);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    if (res?.id) {
      const content = await this.classInfoRepository.delete(id);
      if (content.affected === 1) {
        return {};
      }
      throw new ForbiddenException('删除失败！');
    }
    throw new ForbiddenException('班级信息不存在！');
  }

  findOne(id: number) {
    return this.classInfoRepository.findOne({ where: { id } });
  }
}
